/**
 * TextureLoader takes the name of an images list file, and loads all images
 * from that list. images loaded can be of four different types: o - a single
 * image n - a numbered list of images s - a number of images loaded as a
 * graphics strip - such as a gif with several images in it g - a group of
 * images each with different names
 * @author Owner
 */
package com.dalonedrow.utils;

import java.io.BufferedReader;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.dalonedrow.pooled.PooledStringBuilder;
import com.dalonedrow.pooled.StringBuilderPool;

/**
 * @author DaLoneDrau
 */
public final class TextLoader {
	/** the one and only instance of the <code>TextLoader</code> class. */
	private static TextLoader	instance;
	/**
	 * Gives access to the singleton instance of {@link TextLoader}.
	 * @return {@link TextLoader}
	 */
	public static TextLoader getInstance() {
		if (TextLoader.instance == null) {
			TextLoader.instance = new TextLoader();
		}
		return TextLoader.instance;
	}
	/**
	 * Gives access to the singleton instance of {@link TextLoader}.
	 * @return {@link TextLoader}
	 */
	public static TextLoader getInstance(final String folder) {
		if (TextLoader.instance == null) {
			TextLoader.instance = new TextLoader();
		}
		instance.setLibraryFolder(folder);
		return TextLoader.instance;
	}
	/** the folder containing the image library. */
	private String	libraryFolder;
	/**
	 * Loads a text file and returns the text contained therein.
	 * @param fileName the name of the file
	 * @return {@link String}
	 * @throws Exception if an error occurs
	 */
	public String loadText(final String fileName) throws Exception {
		String text = null;
		PooledStringBuilder sb =
				StringBuilderPool.getInstance().getStringBuilder();
		sb.append(libraryFolder);
		sb.append("/");
		sb.append(fileName);
		FileHandle file = Gdx.files.internal(sb.toString());
		sb.setLength(0);
		// logger.info("loadImage(" + filePath + ")");
		try {
			final int defaultCharBufferSize = 8192;
			BufferedReader input = file.reader(defaultCharBufferSize);
			String inText = ""; // String object to read
			// in each line of the file
			inText = input.readLine(); // priming read
			while (inText != null) {
				sb.append(inText);
			}
			text = sb.toString();
			sb.setLength(0);
			input.close();
			if (text == null) {
				sb.setLength(0);
				sb.append("ERROR! TextLoader loadText() file ");
				sb.append(fileName);
				sb.append(" cannot be read.");
				Exception ex = new Exception(sb.toString());
				sb.setLength(0);
				sb.returnToPool();
				throw ex;
			}
		} catch (Exception exception) {
			throw exception;
		} // end try-catch block
		return text;
	}
	/**
	 * Sets the location of the library folder.
	 * @param folder the location to set
	 */
	public void setLibraryFolder(final String folder) {
		libraryFolder = folder;
	}
}
